package com.weimob.mcloud.wechatwork.customer.service.check;

import com.alibaba.dubbo.config.annotation.Reference;
import com.weimob.mcloud.wechatwork.core.adapter.enums.uc.UCSourceTypeEnum;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.onecrm.request.AccountGetDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.onecrm.request.GetSuperWidReq;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.onecrm.response.AccountGetBO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.onecrm.response.GetSuperWidResp;
import com.weimob.mcloud.wechatwork.core.adapter.service.OneCrmAdapterService;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.Customer;
import com.weimob.mcloud.wechatwork.core.entity.relation.employee.Employee;
import com.weimob.mcloud.wechatwork.core.service.employee.EmployeeService;
import com.weimob.mcloud.wechatwork.customer.externalDependencyProxy.usermanagement.EmployeeProxy;
import com.weimob.mcloud.wechatwork.customer.service.user.exception.BizException;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.tag.CustomerTagDTO;
import com.weimob.mcloud.wechatwork.customer.third.core.CustomerServiceProxy;
import com.weimob.mcloud.wechatwork.customer.third.customer.CustomerThird;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @author junlong.lv
 * @version 1.0
 * @date 2021/12/21 1:06 下午
 */
@Component
@Slf4j
public class TagCheckService {

    @Reference
    private EmployeeService employeeService;

    @Autowired
    private CustomerServiceProxy customerServiceProxy;

    @Reference
    private OneCrmAdapterService oneCrmAdapterService;

    @Autowired
    private CustomerThird customerThird;

    @Autowired
    private EmployeeProxy employeeProxy;

    public void fillCustomer(PrivateSphere privateSphere, CustomerTagDTO customerTagDTO) {
        if (StringUtils.isBlank(customerTagDTO.getExternalUserId()) && StringUtils.isBlank(customerTagDTO.getCustomerId())) {
            return;
        }

        if (StringUtils.isBlank(customerTagDTO.getExternalUserId()) || StringUtils.isBlank(customerTagDTO.getCustomerId())) {
            try {
                List<Customer> customerResponses = customerServiceProxy.fetchCustomerByIds(customerTagDTO.getCustomerId(), customerTagDTO.getExternalUserId(), privateSphere);
                if (CollectionUtils.isNotEmpty(customerResponses)) {
                    customerTagDTO.setExternalUserId(customerResponses.get(0).getExternalUserid());
                    customerTagDTO.setCustomerId(customerResponses.get(0).getId());
                }
            } catch (Exception e) {
                log.error("查询客户信息失败,error", e);
            }
        }

        Long wid = customerTagDTO.getWid();
        if (Objects.isNull(wid)) {
            wid = customerThird.getSuperWid(privateSphere.getBosId(), customerTagDTO.getExternalUserId(), privateSphere.getCorpId());
            customerTagDTO.setWid(wid);
        }
    }

    public void checkCustomer(PrivateSphere privateSphere, CustomerTagDTO customerTagDTO) {
        if (StringUtils.isBlank(customerTagDTO.getExternalUserId()) && StringUtils.isBlank(customerTagDTO.getCustomerId())) {
            throw new BizException("外部联系人id不允许为空");
        }

        if (StringUtils.isBlank(customerTagDTO.getExternalUserId()) || StringUtils.isBlank(customerTagDTO.getCustomerId())) {
            try {
                List<Customer> customerResponses = customerServiceProxy.fetchCustomerByIds(customerTagDTO.getCustomerId(), customerTagDTO.getExternalUserId(), privateSphere);
                if (CollectionUtils.isNotEmpty(customerResponses)) {
                    customerTagDTO.setExternalUserId(customerResponses.get(0).getExternalUserid());
                    customerTagDTO.setCustomerId(customerResponses.get(0).getId());
                }
            } catch (Exception e) {
                log.error("查询客户信息失败, error", e);
            }
        }

        Long wid = customerTagDTO.getWid();
        if (Objects.isNull(wid)) {
            wid = getWid(privateSphere.getBosId(), customerTagDTO.getExternalUserId(), privateSphere.getCorpId());
            customerTagDTO.setWid(wid);
        }
    }

    public void checkUser(PrivateSphere privateSphere, CustomerTagDTO customerTagDTO) {

        String orgUserId = customerTagDTO.getOrgUserId();
        if (StringUtils.isBlank(orgUserId) && StringUtils.isNotBlank(customerTagDTO.getUserId())) {
            orgUserId = getOrgUserId(privateSphere, customerTagDTO.getUserId());
            customerTagDTO.setOrgUserId(orgUserId);
        }
    }

    private String getOrgUserId(PrivateSphere privateSphere, String userId) {
        //通过userId查询orgUserId

        Employee employee = employeeProxy.fetchEmployeeById(privateSphere, userId, null);
        if (employee != null) {
            return employee.getId();
        }

        return null;
    }

    private Long getWid(Long bosId, String externalUserId, String corpId) {
        if (StringUtils.isBlank(externalUserId) || Objects.isNull(bosId) || StringUtils.isBlank(corpId)) {
            return null;
        }

        //1、获取外部联系人wid
        AccountGetDTO accountGetDTO = new AccountGetDTO();
        accountGetDTO.setBosId(bosId);
        accountGetDTO.setOpenId(externalUserId);
        accountGetDTO.setUcSourceTypeEnum(UCSourceTypeEnum.WORK_WEIXIN_EXTERNAL_USERID);
        accountGetDTO.setAppId(corpId);

        AccountGetBO userChannelInfoDTO = SoaUtil.unpack(oneCrmAdapterService.getAccountByOpenId(accountGetDTO));
        if (Objects.isNull(userChannelInfoDTO)) {
            return null;
        }

        Long wid = userChannelInfoDTO.getWid();

        // 查询主wid
        GetSuperWidReq getSuperWidReq = new GetSuperWidReq();
        getSuperWidReq.setBosId(bosId);
        getSuperWidReq.setWid(wid);
        SoaResponse<GetSuperWidResp, ?> superWidRespSoaResponse = oneCrmAdapterService.getSuperWid(getSuperWidReq);
        GetSuperWidResp superWidResp = SoaUtil.unpack(superWidRespSoaResponse);
        if (Objects.nonNull(superWidResp) && Objects.nonNull(superWidResp.getSuperWid())) {
            return superWidResp.getSuperWid();
        }

        return wid;
    }

}
